package edu.friday.controller;

import edu.friday.common.constant.UserConstants;
import edu.friday.common.result.RestResult;
import edu.friday.common.result.TableDataInfo;
import edu.friday.model.vo.SysRoleVO;
import edu.friday.repository.SysRoleRepository;
import edu.friday.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
    @Autowired
    SysRoleService sysRoleService;

    @GetMapping("/list")
    public TableDataInfo list(SysRoleVO sysRoleVO, Pageable pageable) {
        int pageNum = pageable.getPageNumber() - 1;
        pageNum = pageNum <= 0 ? 0 : pageNum;
        pageable = PageRequest.of(pageNum, pageable.getPageSize());
        return sysRoleService.selectRoleList(sysRoleVO, pageable);
    }
    @PostMapping
    public RestResult add(@Validated @RequestBody SysRoleVO sysRoleVO) {
        if (UserConstants.NOT_UNIQUE.equals(sysRoleService.checkRoleNameUnique(sysRoleVO.getRoleName()))) {
            return RestResult.error("新增角色'" + sysRoleVO.getRoleName() + "'失败，角色已存在");
        }
        sysRoleVO.setCreateBy("leiyu");
        boolean flag = sysRoleService.insertRole(sysRoleVO);
        return toAjax(flag ? 1 : 0);
    }

    /**
     * 批量删除 角色
     * @param roleIds
     * @return
     */
    @DeleteMapping("/{roleIds}")
    public RestResult delete(@PathVariable Long[] roleIds) {
        return toAjax(sysRoleService.deleteByRoleIds(roleIds));
    }

    @PutMapping
    public RestResult edit(@Validated @RequestBody SysRoleVO sysRoleVO){
        sysRoleService.checkRoleAllowed(sysRoleVO);
        if(UserConstants.NOT_UNIQUE.equals(sysRoleService.checkRoleNameUnique(sysRoleVO.getRoleName()))){
            return RestResult.error("修改角色 '"+sysRoleVO.getRoleName()+"' 失败，角色已存在");
        }
        sysRoleVO.setUpdateBy("system");
        return toAjax(sysRoleService.updateRole(sysRoleVO));
    }

    /**
     * 获取角色选择框列表
     */
    @GetMapping({"/optionselect", "/"})
    public RestResult optionselect() {
        return RestResult.success(sysRoleService.selectRoleAll());
    }

    /**
     * 根据角色编号获取详细信息
     */
    @GetMapping(value = "/{roleId}")
    public RestResult getInfo(@PathVariable Long roleId) {
        return RestResult.success(sysRoleService.selectRoleById(roleId));
    }

    /**
     * 状态修改
     */
    @PutMapping("/changeStatus")
    public RestResult changeStatus(@RequestBody SysRoleVO role) {
        sysRoleService.checkRoleAllowed(role);
        role.setUpdateBy("system");
        return toAjax(sysRoleService.updateRoleStatus(role));
    }
}
